package com.wan37.auth.component;

import com.wan37.auth.handler.MsgHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 每个Worker代表一个作业线程
 * 每个Worker有自己的阻塞队列
 *
 * @author : luoyong
 * @date : 2020-05-27 16:20
 **/
public class Worker extends Thread {
    private static final Logger logger = LoggerFactory.getLogger(Worker.class);

    public volatile boolean stop = false;

    /**
     * 保存MsgHandler并排队的阻塞队列.
     * 每个worker作业线程都有一个阻塞队列.
     */
    private final BlockingQueue<MsgHandler> msgHandlers = new LinkedBlockingQueue<>();


    @Override
    public void run() {
        while (!stop) {
            MsgHandler msgHandler = null;
            try {
                /**
                 * 获取队列头元素
                 */
                msgHandler = msgHandlers.poll(500, TimeUnit.MILLISECONDS);
                if (msgHandler == null) {
                    continue;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
                msgHandler.execute(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 向队列中添加MsgHandler
     *
     * @param msgHandler
     */
    public void addMsgHandler(MsgHandler msgHandler) {
        if (msgHandler != null) {
            this.msgHandlers.offer(msgHandler);
        }

    }
}
